package edu.umassd.hciproject;

import java.util.ArrayList;

import org.w3c.dom.Text;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import edu.umassd.hciproject.SaveDialogFragment.SaveDialogListener;

public class NewListActivity extends FragmentActivity implements
		View.OnClickListener, SaveDialogListener {

	AutoCompleteTextView textView;
	ImageButton bAdd;
	Button bSave, bShop, bRemove, bClear;
	ListView list;
	String listName;
	MyListsManager manager;
	boolean changed = false;
	public final static String[] options = { "View", "Delete" };
	ArrayAdapter<String> listAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_new_list);

		listName = getIntent().getStringExtra(MyListsActivity.MY_LIST_NAME_KEY);
		if (listName != null)
			setTitle(listName);

		manager = new MyListsManager(this);

		// Get a reference to the AutoCompleteTextView in the layout
		textView = (AutoCompleteTextView) findViewById(R.id.searchBox);
		// Get the string array
		String[] products = getResources().getStringArray(
				R.array.products_array);

		// Create the adapter and set it to the AutoCompleteTextView
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, products);
		textView.setAdapter(adapter);

		list = (ListView) findViewById(R.id.lvNewList);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// Toast.makeText(NewListActivity.this, "List item clicked",
				// Toast.LENGTH_SHORT).show();
			}
		});

		ArrayList<String> myProducts = getIntent().getStringArrayListExtra(
				MyListsActivity.MY_LIST_PRODUCTS_KEY);
		if (myProducts == null) {// if none found
			if (listName == null)
				myProducts = new ArrayList<String>(); // makes it an empty list
			else
				myProducts = manager.getList(listName);
		}
		listAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, myProducts);

		list.setAdapter(listAdapter);
		list.setItemsCanFocus(true);
		list.setChoiceMode(ListView.CHOICE_MODE_NONE);

		bAdd = (ImageButton) findViewById(R.id.bAddProduct);

		bAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String product = textView.getText().toString();
				if (product.length() == 0)
					return;
				listAdapter.add(product);
				listAdapter.notifyDataSetChanged();
				list.setItemChecked(listAdapter.getCount() - 1, false);
				list.smoothScrollToPosition(list.getCount() - 1);
				InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
				textView.clearFocus();
				list.requestFocus();
				textView.getText().clear();
				setChanged(true);
			}
		});

		bRemove = (Button) findViewById(R.id.bRemoveProduct);

		bRemove.setOnClickListener(new View.OnClickListener() {
			boolean deleting = false;
			ListView itemsView;
			ArrayList<String> removing, items;

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// long[] selected = list.getCheckedItemIds();
				// if (selected.length == 0)
				// return;
				AlertDialog.Builder builder = new AlertDialog.Builder(NewListActivity.this);
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
						//ArrayAdapter<String> adapter = (ArrayAdapter<String>) itemsView.getAdapter();
						int count = items.size();
						ArrayAdapter<String> newAdapter = new ArrayAdapter<String>(
								NewListActivity.this,
								android.R.layout.simple_list_item_1);
						items.removeAll(removing);
						for (int i = 0; i < items.size(); i++) {
								newAdapter.add(items.get(i));
						}
						listAdapter.clear();
						listAdapter = newAdapter;
						list.setAdapter(listAdapter);
						list.setChoiceMode(ListView.CHOICE_MODE_NONE);
						list.setItemsCanFocus(true);
						listAdapter.notifyDataSetChanged();
						setChanged(count != newAdapter.getCount());
						
					}
				});
				/*
				itemsView = new ListView(NewListActivity.this);
				itemsView.setAdapter(new ArrayAdapter<String>(
						NewListActivity.this,
						android.R.layout.simple_list_item_multiple_choice,
						getProducts()));
				itemsView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				builder.setView(itemsView);
				*/
				items = getProducts();
				removing = new ArrayList<String>();
				builder.setMultiChoiceItems(items.toArray(new String[1]), null, new DialogInterface.OnMultiChoiceClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							removing.add(items.get(which));
						}
					}
				});
				builder.show();
				/*
				if (!deleting) {
					listAdapter = new ArrayAdapter<String>(
							NewListActivity.this,
							android.R.layout.simple_list_item_multiple_choice,
							getProducts());
					list.setAdapter(listAdapter);
					list.clearChoices();
					list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
					list.setItemsCanFocus(false);
					bRemove.setText("Delete");
					bAdd.setEnabled(false);
					bSave.setEnabled(false);
					bShop.setEnabled(false);
					deleting = true;
				} else {
					int count = listAdapter.getCount();
					ArrayAdapter<String> newAdapter = new ArrayAdapter<String>(
							NewListActivity.this,
							android.R.layout.simple_list_item_1);
					for (int i = 0; i < count; i++) {
						if (!list.isItemChecked(i))
							newAdapter.add(listAdapter.getItem(i));
					}
					listAdapter.clear();
					listAdapter = newAdapter;
					list.setAdapter(listAdapter);
					list.setChoiceMode(ListView.CHOICE_MODE_NONE);
					list.setItemsCanFocus(true);
					listAdapter.notifyDataSetChanged();
					bRemove.setText("Remove Multiple");
					setChanged(count != newAdapter.getCount());
					deleting = false;
				}
				*/
			}
		});

		bSave = (Button) findViewById(R.id.bSaveList);
		bSave.setEnabled(false);
		bSave.setOnClickListener(this);

		bShop = (Button) findViewById(R.id.bShop);
		bShop.setOnClickListener(this);

		setChanged(false);

	}

	protected void updateButtons() {
		// TODO Auto-generated method stub
		bAdd.setEnabled(true);
		bShop.setEnabled(true);
		bRemove.setEnabled(!listAdapter.isEmpty());
		bSave.setEnabled(changed);
	}

	private void setChanged(boolean b) {
		// TODO Auto-generated method stub
		changed = b;
		updateButtons();
		/*
		bSave.setEnabled(b);
		bSave.setClickable(b);
		bSave.setTextColor(b ? Color.BLACK : Color.GRAY);
		*/
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		getIntent().putStringArrayListExtra(
				MyListsActivity.MY_LIST_PRODUCTS_KEY, getProducts());
		if (listName != null)
			getIntent().putExtra(MyListsActivity.MY_LIST_NAME_KEY, listName);
		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_new_list, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.bShop)
			startActivity(new Intent(this, StoreSearchActivity.class));
		else if (v.getId() == R.id.bSaveList) {
			if (!changed)
				return;
			if (listName == null) {
				SaveDialogFragment dialog = new SaveDialogFragment();
				dialog.show(getSupportFragmentManager(), "SaveListDialog");
			} else {
				manager.putList(listName, getProducts());
				setChanged(false);
				Toast t = Toast.makeText(this, "List \"" + listName
						+ "\" updated", Toast.LENGTH_SHORT);
				t.show();
			}
		}
	}

	private ArrayList<String> getProducts() {
		// TODO Auto-generated method stub
		ArrayList<String> products = new ArrayList<String>();
		for (int i = 0; i < listAdapter.getCount(); i++) {
			products.add(listAdapter.getItem(i));
		}
		return products;
	}

	@Override
	public void onSaveClickListener(DialogFragment dialog, String name) {
		// TODO Auto-generated method stub
		String message = null;
		if (name.length() == 0)
			message = "Unable to save (No name entered)";
		else {
			listName = name;
			setTitle(listName);
			manager.putList(name, getProducts());
			message = "Saved";
			setChanged(false);
		}
		Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
		t.show();
	}

}
